# 对 增删改查操作数据库 封装
import pymysql

class DBTools:
    # 创建工具方法---创建连接
    @staticmethod
    def __creat_connect():
        conn = pymysql.connect(host="211.103.136.244", port=7061, user="student",
                               password="iHRM_student_2022", database="ihrm", charset="utf8")
        return conn

   # 创建工具方法---查一条
    @staticmethod
    def query_one(sql):
        conn = None
        cursor = None
        result = None
        try:
            conn = DBTools.__creat_connect()  # 先创建连接，调用创建连接的函数
            cursor = conn.cursor()  # 创建游标
            cursor.execute(sql)  # 执行sql语句
            result = cursor.fetchone()

        except Exception as e:
            print("查询出错：", e)
        finally:
            cursor.close()
            conn.close()
            return result

    # 创建工具方法---增删改
    @staticmethod
    def db_idu(sql):
        conn = None
        cursor = None
        try:
            conn = DBTools.__creat_connect()
            cursor = conn.cursor()
            cursor.execute(sql)
            conn.commit()

        except Exception as error:
            conn.rollback()
            print("查询出错：", error)
        finally:
            conn.close()
            cursor.close()







if __name__ == "__main__":
    result1 = DBTools.query_one("select id from bs_user where mobile = '13800000002';")
    print("查询结果为：", result1)
    result2 = DBTools.db_idu("delete from bs_user where id = 17")
    print("删除成功：", result2)
    result3 = DBTools.db_idu("insert into bs_user (mobile,username) values('13296090878'，’张三‘);")
    print("增加成功：", result3 )

# 普通方法必须实例化才能调用
# 静态方法和类方法都不需要实例，类.方法  调用
# 静态方法装饰器 @staticmethod
# 类方法装饰器：@classmethod  一般用于修改
